package java8;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author lzy
 * Create DateTime: 2018/7/18 15:57
 * @version v1.0
 * <p>
 * Java8 内置的四大核心函数式接口：
 * <p>
 * Consumer<T>:消费型接口
 * void accept(T t);
 * <p>
 * Supplier<T>:供给型接口
 * T get();
 * <p>
 * Function<T,R>:函数型接口
 * R apply(T t);
 * <p>
 * Predicate<T>:断言型接口
 * boolean test(T t);
 */
public class TestLambda4 {
    // consumer
    @Test
    public void test1() {
        happy(1000, m -> System.out.println("购物消费" + m));
    }

    private void happy(double money, Consumer<Double> con) {
        con.accept(money);
    }

    // supplier
    @Test
    public void test2() {
        getNumberList(10, () -> new Random().nextInt(100)).forEach(System.out::println);
    }

    // 需求：产生指定个数的整数，并放入到集合中
    private List<Integer> getNumberList(int num, Supplier<Integer> sup) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            list.add(sup.get());
        }
        return list;
    }

    // function
    @Test
    public void test3() {
        String res = strHandler("\t\t\t afadfasfd ", str -> str.trim().toUpperCase());
        System.out.println(res);
    }

    // 用于处理字符串
    private String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }

    // predicate
    @Test
    public void test4() {
        List<String> strList = Arrays.asList("Hello", "Atdfas", "lambda", "aa", "a", "df");
        filterStr(strList, s -> s.length() > 3).forEach(System.out::println);
    }

    // 需求：处理字符串，将满足条件的字符串添加到集合中
    private List<String> filterStr(List<String> list, Predicate<String> pre) {
        List<String> strList = new ArrayList<>();
        for (String str : list) {
            if (pre.test(str)) {
                strList.add(str);
            }
        }
        return strList;
    }
}
